<template>
  <div class="upload-files">
    <el-upload
      v-model:file-list="_fileList"
      action="#"
      :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
      :multiple="true"
      :disabled="self_disabled"
      :limit="limit"
      :http-request="handleHttpUpload"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :drag="drag"
      :accept="fileType.join(',')"
    >
      <el-icon v-if="drag" class="el-icon--upload"><upload-filled /></el-icon>
      <div v-if="drag" class="el-upload__text">拖拽文件/点击上传</div>
      <div v-if="!drag">
        <el-button type="primary">选择文件</el-button>
      </div>
      <template #file="{ file }">
        <div class="flex-between">
          <span>{{ file.name }}</span>
          <el-button type="danger" link @click="removeFiles(file)">删除</el-button>
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts" name="UploadFiles">
import { ref, computed, inject, watch } from "vue";
import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions } from "element-plus";
import { ElNotification, formContextKey, formItemContextKey } from "element-plus";
import { uploadFiles } from "@/api/modules/upload";

interface UploadFileProps {
  fileList: UploadedFile[];
  api?: (params: any) => Promise<any>; // 上传文件的 api 方法，一般项目上传都是同一个 api 方法，在组件里直接引入即可 ==> 非必传
  drag?: boolean; // 是否支持拖拽上传 ==> 非必传（默认为 true）
  disabled?: boolean; // 是否禁用上传组件 ==> 非必传（默认为 false）
  limit?: number; // 最大文件上传数 ==> 非必传（默认为 5张）
  fileSize?: number; // 文件大小限制 ==> 非必传（默认为 5M）
  fileType?: any[]; // 文件类型限制 ==> 非必传（默认为 ["image/jpeg", "image/png", "image/gif"]）
}

const props = withDefaults(defineProps<UploadFileProps>(), {
  fileList: () => [],
  limit: 10,
  fileSize: 50,
  drag: true,
  fileType: () => []
});

// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled || formContext?.disabled;
});

interface UploadedFile extends Array<UploadUserFile> {
  id?: string;
}

const _fileList = ref<UploadedFile[]>(props.fileList);

// 监听 props.fileList 列表默认值改变
watch(
  () => props.fileList,
  (n: UploadedFile[]) => {
    _fileList.value = n;
  }
);

function removeFiles(row) {
  _fileList.value = _fileList.value.filter(item => item.id !== row.id);
}

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;

  if (!imgSize)
    setTimeout(() => {
      ElNotification({
        title: "温馨提示",
        message: `上传文件大小不能超过 ${props.fileSize}M！`,
        type: "warning"
      });
    }, 0);
  return imgSize;
};

/**
 * @description 文件上传
 * @param options upload 所有配置项
 * */
const handleHttpUpload = async (options: UploadRequestOptions) => {
  let formData = new FormData();
  formData.append("file", options.file);
  try {
    const api = props.api ?? uploadFiles;
    const { data } = await api(formData);
    const [file] = data;
    options.onSuccess(file);
  } catch (error) {
    options.onError(error as any);
  }
};

/**
 * @description 文件上传成功
 * @param response 上传响应结果
 * @param uploadFile 上传的文件
 * */
const emit = defineEmits<{
  "update:fileList": [value: UploadedFile[]];
}>();
const uploadSuccess = (response: { fileUrl: string; id: string } | undefined, uploadFile: UploadFile) => {
  if (!response) return;
  uploadFile.url = response.fileUrl;
  console.log(response);
  Object.assign(uploadFile, { id: response.id });
  emit("update:fileList", _fileList.value);
  // 调用 el-form 内部的校验方法（可自动校验）
  formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
  ElNotification({
    title: "温馨提示",
    message: "文件上传成功！",
    type: "success"
  });
};

/**
 * @description 文件上传错误
 * */
const uploadError = () => {
  ElNotification({
    title: "温馨提示",
    message: "文件上传失败，请您重新上传！",
    type: "error"
  });
};

/**
 * @description 文件数超出
 * */
const handleExceed = () => {
  ElNotification({
    title: "温馨提示",
    message: `当前最多只能上传 ${props.limit} 张文件，请移除后上传！`,
    type: "warning"
  });
};
</script>

<style scoped lang="scss">
.upload-files {
  width: 100%;
  &::v-deep(.el-upload) {
    width: 100%;
  }

  &:deep(.el-upload-list) {
    margin-top: 10px;
    .el-upload-list__item {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .trigger-title {
    flex: 1;
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    flex: 1;
  }
}
.btn {
  width: 100%;
}
</style>
